import React, {Component} from 'react';
import {Modal, Row, Col, Label} from 'reactstrap';
import {AvFeedback, AvForm, AvGroup, AvInput, AvField} from "availity-reactstrap-validation";
import Flight from './Components/Flight';
import Housing from "./Components/Housing";
import Travel from "./Components/Travel";
import Todo from "./Components/Todo";
import EventTabButton from "../../../../../components/Buttons/EventTabButton";
import {CloseIcon, DeleteIcon, PlusIcon} from "../icons";
import Flatpickr from "react-flatpickr";
import {Russian} from 'flatpickr/dist/l10n/ru.js';

class AddScheduleForm extends Component {

    constructor(props) {
        super(props);
        this.state = {
            Validate: {
                name: false,
                begin_date: false,
                begin_time: false,
            },
        };
    }

    close = () => {
        this.props.actions.setModal({
            isOpen: false
        });
        this.props.actions.cleanScheduleForm();
        this.setState({
            Validate: {
                name: false,
                begin_date: false,
                begin_time: false,
            },
            begin_date_valid: true,
            begin_time_valid: true,
        })
    };
    setModal = () => {
        this.props.actions.setModal({
            isOpen: true,
            type: 'add'
        })
    };

    addPassengerToState = () => {
        this.props.actions.setScheduleValue('newPassenger', {
            ...this.props.state.newPassenger,
            firstnameValidate: this.props.state.newPassenger.firstname.trim().length === 0
        });

        if (this.props.state.newPassenger.firstname.trim().length) {
            this.props.actions.setSchedulePassenger({
                firstname: this.props.state.newPassenger.firstname,
                lastname: this.props.state.newPassenger.lastname,
                reservation_number: this.props.state.newPassenger.reservation_number,
            });

            this.props.actions.setScheduleValue('newPassenger', {
                firstname: '',
                firstnameValidate: false,
                lastname: '',
                reservation_number: '',
            });
        }
    };

    validatePassengersFromAdd = () => {
        for (let elem of this.props.state.scheduleFormData.schedule_passengers)
            if (elem.firstname.trim() === '')
                return false;
        return true
    };
    setScheduleFormState = (e) => {
        if (this.props.actions.setScheduleFormState(e.target.name, e.target.value))
            if (e.target.name === 'schedule_type')
                this.props.actions.cleanScheduleFormWithoutName();
    };
    formatDate = (e) => {
        let date = new Date(e);
        let d = date.getDate();
        let m = date.getMonth() + 1;
        let y = date.getFullYear();
        return y + '-' + (m <= 9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
    };
    formatTime = (e) => {
        let date = new Date(e);
        let h = date.getHours();
        let m = date.getMinutes();
        return (h <= 9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m) + ':00';
    };
    setScheduleFormStateTime = (e, name) => {
        this.props.actions.setScheduleFormState(name, this.formatTime(e[0]))
    };

    setScheduleFormStateDate = (e, name) => {
        this.props.actions.setScheduleFormState(name, this.formatDate(e))
    };
    handleValidSubmitEvent = () => {
        this.setState({
            Validate: {
                ...this.state.Validate,
                name: (!this.props.state.scheduleFormData.name || this.props.state.scheduleFormData.name.trim().length === 0),
                begin_date: (!this.props.state.scheduleFormData.begin_date || this.props.state.scheduleFormData.begin_date.trim().length === 0),
                begin_time: (!this.props.state.scheduleFormData.begin_time || this.props.state.scheduleFormData.begin_time.trim().length === 0),
            }
        }, () => {
            if ((!this.state.Validate.name && !this.state.Validate.begin_date && !this.state.Validate.begin_time && this.validatePassengersFromAdd())) {
                this.setState({Validate: {name: false, begin_date: false, begin_time: false,}, begin_date_valid: true, begin_time_valid: true,})
                if (this.props.state.modal.type === 'update') {
                    this.props.actions.updateSchedule(this.props.state.scheduleFormData);
                } else {
                    this.props.actions.storeSchedule(this.props.eventId, this.props.state.scheduleFormData)
                }
            }
        })
    };
    selectData = [
        {key: 'schedule_todo', value: 'Добавить дела'},
        {key: 'schedule_flight', value: 'Добавить авиарейс'},
        {key: 'schedule_housing', value: 'Добавить место проживания'},
        {key: 'schedule_travel', value: 'Добавить поездку'}
    ];
    title = {
        schedule_todo: 'Добавить дело',
        schedule_flight: 'Добавить рейс',
        schedule_housing: 'Добавить жилье',
        schedule_travel: 'Добавить поездку'
    };
    openedModal = () => {
        if (this.props.state.modal.type === 'update') {
            this.props.actions.getScheduleFormData(this.props.state.modal.scheduleId);
            this.setState({
                ...this.props.state.scheduleFormData
            })
        }
    };
    setStateValidate = (key, value) => {
        this.setState({
            Validate: {
                ...this.state.Validate,
                [key]: value
            }
        })
    };

    render() {
        const scheduleType = this.props.state.scheduleFormData && this.props.state.scheduleFormData.schedule_type;
        return (
            <>
                <EventTabButton
                    onClick={this.setModal}
                    text="Добавить пункт"
                    classNameButton="tab-contact-add-button schedule-modal-button"
                />
                <Modal
                    isOpen={this.props.state.modal.isOpen}
                    toggle={this.close}
                    className={`schedule-modal-block modal-dialog-centered ${scheduleType === 'schedule_todo' ? 'schedule-modal-small' : 'schedule-modal-normal'}`}
                    onOpened={this.openedModal}>
                    <AvForm className="authentication-form">
                        <div className="schedule-modal">
                            <div className="schedule-modal-head">
                                <Row>
                                    <Col md={9}>
                                        <span>{this.title[scheduleType]}</span>
                                    </Col>
                                    <Col md={3}>
                                        <div onClick={this.close} className="schedule-modal-head-close">
                                            <CloseIcon/>
                                        </div>
                                    </Col>
                                </Row>
                            </div>
                            <div className="modal-schedule-content">
                                <Row>
                                    <Col md={5}>
                                        <div className="modal-schedule-input-name">
                                            <AvGroup className={'event-form-item'}>
                                                <AvInput
                                                    className="popup-modal-input schedule-input-height"
                                                    autoComplete="off"
                                                    type="text"
                                                    name="name"
                                                    onInput={(e) => {
                                                        this.setScheduleFormState(e);
                                                        if(this.state.Validate.name) this.setState({Validate: {...this.state.Validate, name: false}})}
                                                    }
                                                    id="name"
                                                    value={this.props.state.scheduleFormData.name}
                                                    placeholder="Введите название"
                                                    invalid={this.state.Validate.name}
                                                />
                                            </AvGroup>
                                        </div>
                                        {scheduleType === 'schedule_todo' &&
                                        <div className="modal-schedule-input-desc">
                                            <Todo
                                                scheduleFormData={this.props.state.scheduleFormData}
                                                setScheduleFormState={this.props.actions.setScheduleFormState}
                                            />
                                        </div>
                                        }
                                    </Col>
                                    <Col md={7}>
                                        <div className="modal-schedule-input-business">
                                            <AvField
                                                className="event-form-item popup-modal-input schedule-input-height"
                                                type="select"
                                                name="schedule_type"
                                                id="schedule_type"
                                                value={scheduleType}
                                                onChange={e => this.setScheduleFormState(e)}
                                                disabled={this.props.state.modal.type === 'update'}
                                            >
                                                {this.selectData.map(item => <option
                                                    value={item.key} key={item.key}>{item.value}</option>)}
                                            </AvField>
                                        </div>
                                        {scheduleType === 'schedule_todo' &&
                                        <div className="modal-schedule-date-block">
                                            <Row>
                                                <Col md={6}>
                                                    <div className="modal-schedule-date">
                                                        <AvGroup className={'event-form-item'} required>
                                                            <Label for="begin_date" className="schedule-label">Дата
                                                                начала</Label>
                                                            <Flatpickr
                                                                value={this.props.state.scheduleFormData.begin_date}
                                                                options={{
                                                                    dateFormat: "Y-m-d",
                                                                    locale: Russian,
                                                                }}
                                                                onChange={(e) => {
                                                                    this.setScheduleFormStateDate(e, 'begin_date');
                                                                    if(this.state.Validate.begin_date) this.setState({Validate: {...this.state.Validate, begin_date: false}})
                                                                }}
                                                                className={`form-control popup-modal-input schedule-input-height ${this.state.Validate.begin_date && 'input-invalid'}`}
                                                                name="begin_date"
                                                                id="begin_date"
                                                                placeholder="Дата"
                                                                required
                                                            />
                                                            <AvFeedback>Поле обязательно для заполнения!</AvFeedback>
                                                        </AvGroup>
                                                    </div>
                                                </Col>
                                                <Col md={6}>
                                                    <div className="modal-schedule-time">
                                                        <AvGroup className={'event-form-item'}>
                                                            <Label for="begin_time" className="schedule-label">Время
                                                                начала</Label>
                                                            <Flatpickr
                                                                value={this.props.state.scheduleFormData.begin_time}
                                                                options={{
                                                                    enableTime: true,
                                                                    noCalendar: true,
                                                                    dateFormat: "H:i",
                                                                    time_24hr: true,
                                                                }}
                                                                onChange={(e) => {
                                                                    this.setScheduleFormStateTime(e, 'begin_time');
                                                                    if(this.state.Validate.begin_time) this.setState({Validate: {...this.state.Validate, begin_time: false}})
                                                                }}
                                                                className={`form-control popup-modal-input schedule-input-height ${this.state.Validate.begin_time && 'input-invalid'}`}
                                                                name="begin_time"
                                                                id="begin_time"
                                                                placeholder="Время"
                                                                required
                                                            />
                                                            <AvFeedback>Поле обязательно для заполнения!</AvFeedback>
                                                        </AvGroup>
                                                    </div>
                                                </Col>
                                            </Row>
                                        </div>
                                        }
                                    </Col>
                                </Row>
                                {scheduleType === 'schedule_flight' &&
                                <Flight
                                    actions={this.props.actions}
                                    state={this.props.state}
                                    Validate={this.state.Validate}
                                    setStateValidate={this.setStateValidate}
                                />
                                }
                                {scheduleType === 'schedule_housing' &&
                                <Housing
                                    state={this.props.state}
                                    actions={this.props.actions}
                                    Validate={this.state.Validate}
                                    setStateValidate={this.setStateValidate}
                                />
                                }
                                {scheduleType === 'schedule_travel' &&
                                <Travel
                                    actions={this.props.actions}
                                    state={this.props.state}
                                    Validate={this.state.Validate}
                                    setStateValidate={this.setStateValidate}
                                />
                                }
                                <div
                                    className={`modal-schedule-footer-buttons ${scheduleType !== 'schedule_todo' ? 'modal-schedule-buttons' : ''}`}>
                                    {scheduleType !== 'schedule_todo' &&
                                    <div className="flight-passengers-button cursor-pointer">
                                        <PlusIcon/>
                                        <span
                                            className="add-new-ticket-fields-text"
                                            onClick={() => this.props.state.addPassenger ? this.addPassengerToState() : this.props.actions.setScheduleValue('addPassenger', !this.props.state.addPassenger)}
                                        >
                                                {scheduleType === 'schedule_housing' ? 'Добавить гостя' : 'Добавить пассажира'}
                                            </span>
                                    </div>
                                    }
                                    <div className="tab-contacts-modal-footer">
                                        <EventTabButton
                                            text="Удалить"
                                            icon={DeleteIcon}
                                            onClick={this.close}
                                            classNameButton="modal-schedule-button tab-contact-modal-btn-delelte"
                                            classNameText="tab-contact-modal-button-delete-text"
                                        />
                                        <EventTabButton
                                            text="Сохранить"
                                            onClick={this.handleValidSubmitEvent}
                                            classNameButton="modal-schedule-button tab-contact-modal-btn-save"
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </AvForm>
                </Modal>
            </>
        )
    }
}

export default (AddScheduleForm)
